<template>
  <q-dialog  v-model="printerDiag"> 
    <NFCPrinter v-if="qr_location_id" :qr_location_id="qr_location_id"></NFCPrinter>
  </q-dialog>
  <MyDialog
    :mode="props.mode == 'fitment' ? 'Deport' : 'Equipment'"
    :title="`${props.mode}`"
    :submit="callDepotFitment"
  >
    <q-card-section>
      <div class="row justify-between">
        <q-input
          class="input-css q-ma-sm col-8"
          label="Stock Code"
          :dense="true"
          borderless
          v-model="parent_stock_code"
        ></q-input>
        <div class="text-sm q-pa-sm col-2 fac" v-if="props.mode == 'fitment'">
          <img :src="searchIcon" alt="" class="searchIcon" @click="openSearchDepot">
          <q-icon
            name="qr_code"
            size="40px"
            class="cursor-pointer"
            color="primary"
            @click="scanDiag = true"
            style="margin-right: 20px;"
          ></q-icon>
          <q-dialog  v-model="scanDiag">
            <OpenCam @submit="(v) => onSubmit(v)"></OpenCam>
          </q-dialog>
        </div>
        <q-input
          class="input-css q-ma-sm col-8"
          label="Serial No."
          :dense="true"
          borderless
          v-model="parent_serial_no"
        ></q-input>
        <q-select
          v-if="props.mode == 'fitment'"
          class="input-css q-ma-sm col-8"
          label="Location"
          :dense="true"
          borderless
          v-model="new_car"
          :options="locationOptions"
          use-input
          @filter="filterLocFn"
        ></q-select>
        <div class="text-sm q-pa-sm col- fac" v-if="props.mode == 'fitment'">
          <q-btn
            v-if="new_car"
            size="sm"
            class="q-ma-sm e-form-btn cap"
            @click="printQrCode()"
            >print</q-btn
            >
          <q-icon
            name="qr_code"
            size="40px"
            class="cursor-pointer"
            color="primary"
            @click="scanCarDiag = true"
          ></q-icon>
          <q-dialog  v-model="scanCarDiag">
            <OpenCam @submit="(v) => onSubmitCar(v)"></OpenCam>
          </q-dialog>
        </div>
      </div>
    </q-card-section>
  </MyDialog>
  <!-- depot 搜索弹窗 -->
  <q-dialog  v-model="dialogResult">
    <q-card style="width: 50vw;max-width:58vw;" class="overflow-hidden card-radius" >
      <q-toolbar class="popup-header">
        <q-toolbar-title class="q-ma-md cap">
          Search  Result
        </q-toolbar-title>
        <q-space />
          <q-btn
          icon="close"
          size="lg"
          flat
          round
          dense
          v-close-popup
          />
      </q-toolbar>
        <div class="content mt20">
          <div class="flex-center">
            <div class="flex1 text-sm q-pa-sm">
              <div class="row">
                <div class="col-4 fac">Stock Code:</div>
                <div class="col-8">
                  <q-input
                    class="input-css"
                    borderless
                    dense
                    v-model="searchInfo.stock_code"
                  >
                    <template v-slot:append>
                      <img class="delImgClass" :src="delImg" alt="" v-if="searchInfo.stock_code" @click="searchInfo.stock_code = ''">
                    </template>
                  </q-input>
                </div>
              </div>
            </div>
            <div class="flex1 text-  q-pa-sm">
              <div class="row">
                <div class="col-4 fac">Serial No:</div>
                <div class="col-8">
                  <q-input
                    class="input-css"
                    borderless
                    dense
                    v-model="searchInfo.serial_no"
                  >
                    <template v-slot:append>
                      <img class="delImgClass" :src="delImg" alt="" v-if="searchInfo.serial_no" @click="searchInfo.serial_no = ''">
                    </template>
                  </q-input>
                </div>
              </div>
            </div>
          </div>
        </div>
        <q-card-actions class="justify-evenly q-pa-md">
          <q-btn label="Search" class="default-btn" :loading="tableLoading" @click="showFitmentResult"/>
        </q-card-actions>
        <scroll-area :bot-margin="0">
          <table style="width: 100%">
            <thead>
              <tr>
                <th v-for="item in columns" :key="item">{{ item }}</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td style="padding-left: 40px;">
                    <q-input borderless :label="columns[0]" dense v-model="query.stock_code" filled style="width:85%;">
                        <template v-slot:default>
                            <q-icon name="search" />
                        </template>
                    </q-input>
                </td>
                <td style="padding-left: 40px;">
                    <q-input borderless :label="columns[1]" dense v-model="query.serial_no" filled style="width:85%;">
                        <template v-slot:default>
                            <q-icon name="search" />
                        </template>
                    </q-input>
                </td>
                <td style="padding-left: 40px;">
                    <q-input borderless :label="columns[2]" dense v-model="query.description" filled style="width:85%;">
                        <template v-slot:default>
                            <q-icon name="search" />
                        </template>
                    </q-input>
                </td>
              </tr>
              <tr v-for="item in dataSource" :key="item.id" class="pined-row-seperator">
                <td>{{item.stock_code || '--'}}</td>
                <td>{{item.serial_no || '--'}}</td>
                <td>{{item.description || '--'}}</td>
                <td>
                    <q-btn size="xs" outline rounded color="primary" :loading="item.confirmLoading" label="Confirm" @click="showValue(item)"></q-btn>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="row justify-center q-mt-md q-mb-md">
            <q-pagination
              v-model="tablePagination.page"
              :max="pagesNumber"
              input-class="text-gray-10"
              max-pages="5"
              input
              direction-links
            />
          </div>
      </scroll-area>
    </q-card>
  </q-dialog>

  <!-- depot 确认数据弹窗 -->
  <q-dialog v-model="confirmDialog">
    <q-card style="width: 400px;">
      <div class="title">Prompt</div>
      <q-card-section class="row items-center" style="font-size:16px;">
        <div class="q-ml-sm">Please confirm the Stock Code & Serial No.</div>
      </q-card-section>
      <q-card-section class="row items-center serialNoClass">
        <div class="q-ml-sm">Stock Code：{{confirmData.stock_code || '--'}}</div>
        <div class="q-ml-sm">Serial No.：{{confirmData.serial_no || '--'}}</div>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn flat label="Cancel" @click="confirmDialog = false" color="primary" v-close-popup />
        <q-btn flat label="Confirm" @click="submitDialog" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import delImg from 'src/assets/style/delImgs.png';
import { depotFitment, selectDepotList } from 'src/services/depotService';
import { onMounted, reactive, ref, watch } from 'vue';
import OpenCam from 'src/components/OpenCam.vue';
import { useQuasar } from 'quasar';
import MyDialog from '../container/MyDialog.vue';
import { parseLocationQR, parsePartQR } from 'src/utils/parseQRCodeUtils';
import { listqrmap } from 'src/services/qrMapLocationService';
import { QRLocationMapI, searchDepotType } from 'src/services/type';
import NFCPrinter from 'src/components/printer/NFCPrinter.vue'
import searchIcon from 'src/assets/style/search-icon.jpg'
import ScrollArea from '../ScrollArea.vue';

const props = defineProps<{
  mode: 'fitment' | 'defitment';
  stock_code?: string;
  serial_no?: string;
}>();

const $q = useQuasar();
const parent_stock_code = ref('');
const parent_serial_no = ref('');
const new_car = ref('');
const scanDiag = ref(false);
const scanCarDiag = ref(false);

const locationOptions = ref([])
const locationStringOptions = ref([])

const qr_location_id = ref(null)
const printerDiag = ref(false)
const emit = defineEmits(['update']);

const dialogResult = ref(false);
const searchInfo = ref<searchDepotType>({
  stock_code: '',
  serial_no: ''
});
const dataSource = ref([]); // 数据源
const columns = ref(['Stock Code', 'Serial No', 'Short Description', '']);
const tableLoading = ref(false); // table 加载loading

const stockCodeVal = ref('');
const serialNoVal = ref('');
const descriptionVal = ref('');
const query = ref({
  stock_code: '',
  serial_no: '',
  description: ''
})
const dataSourceCopy = ref([]); // 拷贝一份数据源
const confirmDialog = ref<boolean>(false); // 确认数据弹窗
const confirmData = ref({}); // 存储确认的数据
const state = reactive({
  pagination: {
    page_size: 10 as number,
    page_num: 1 as number,
  },
})
const tablePagination = ref({ rowsPerPage: 10, page: 1 });
const pagesNumber = ref(0);

async function callDepotFitment() {
  try {
    const res = await depotFitment(
      parent_stock_code.value,
      parent_serial_no.value,
      new_car.value
    );
    if (res.data) {
      if (res.data.code == 1) {
        $q.notify({
          color: 'positive',
          message: `${props.mode} success`,
        });
      }
      if (res.data.code == 0) {
        $q.notify({
          color: 'negative',
          message: `${res.data.message}`,
        });
      }
      emit('update', new_car.value);
    }
  } catch (error) {
    console.log(error,'error');
  }
}

const locationQRMap = new Map()

async function initLocationOptions() {
  const res = await listqrmap()
  // console.log(res.data);
  if (res.data){
    locationOptions.value = res.data.map((i:QRLocationMapI)=>{
      locationQRMap.set(i.category + '-' + i.train, i.id)
      return i.category + '-' + i.train
    })
    locationStringOptions.value = [...locationOptions.value]

  }
}

async function onSubmit(string: string) {
  console.log('onSubmit');
  const obj = await parsePartQR(string);
  if (obj){
    parent_stock_code.value = obj.CAT;
    parent_serial_no.value = obj.SN;
  }
    scanDiag.value = false;
}

async function onSubmitCar(string: string) {
  console.log('onSubmitCar');
  const formatString = await parseLocationQR(string);
  console.log(formatString);
  
  if (formatString){
    new_car.value = formatString
  }
  scanCarDiag.value = false;
}

function printQrCode() {
/*   const qr = document.getElementById('qr');
  printQrImg(stock_code); */
  const id = locationQRMap.get(new_car.value)
  qr_location_id.value=id
  printerDiag.value = true

}

onMounted(() => {
  if (props.mode == 'defitment' && props.stock_code && props.serial_no) {
    parent_stock_code.value = props.stock_code;
    parent_serial_no.value = props.serial_no;
    new_car.value = '';
  }
  initLocationOptions()
});

function filterLocFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      locationOptions.value = [...locationStringOptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    locationOptions.value = locationStringOptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}

/**
 * 查询depot列表
 */
const selectDepotListFn = async (isSearch=1)=> {
  let { stock_code, serial_no } = searchInfo.value;
  let searchParams;
  if(isSearch==2) {
    searchParams = {
      stock_code,
      serial_no,
      ...state.pagination,
    }
  }else {
    searchParams = {
      stock_code: parent_stock_code.value || stock_code,
      serial_no: parent_serial_no.value || serial_no,
      ...state.pagination,
    }
  }
  tableLoading.value = true;
  try {
    let res = await selectDepotList(searchParams)
    let { results=[], count=0 } = res.data;
    pagesNumber.value = Math.ceil(count / tablePagination.value.rowsPerPage);
    dataSource.value = results?.map((m:any)=> {
      return {
        ...m,
        confirmLoading: false,
      }
    });
    dataSourceCopy.value = results;
  } catch (error) {
    
  }finally {
    tableLoading.value = false;
  }
}

/**
 * 打开搜索 Depot 弹窗
 */
const openSearchDepot = async ()=> {
  dialogResult.value = true;
  searchInfo.value = {
    stock_code: parent_stock_code.value,
    serial_no: parent_serial_no.value
  }
  selectDepotListFn();
}

/**
 * 搜索 Depot list 数据
 */
const showFitmentResult = async ()=> {
  tableLoading.value = true;
  selectDepotListFn(2);
}

/**
 * 打开确认弹窗
 */
const showValue = (row={} as any)=> {
  row.confirmLoading = true;
  confirmData.value = {};
  setTimeout(()=> {
    row.confirmLoading = false;
    confirmData.value = JSON.parse(JSON.stringify(row));
    confirmDialog.value = true;
  }, 800)
}

watch(query.value, () => {
    // 调用筛选函数
    filterList();
});

interface itemFilterType {
  stock_code: string,
  serial_no: string,
  description: string,
}
const filterList = ()=> {
  dataSource.value = dataSourceCopy.value.filter((item:itemFilterType) => {
    let { stock_code, serial_no, description  } = query.value;
    const conditionCheck =
        item.stock_code.includes(stock_code) &&
        item.serial_no.includes(serial_no) &&
        item.description.includes(description);
        return conditionCheck;
    })
}

/**
 * 确定回显数据
 */
const submitDialog = ()=> {
  let { stock_code, serial_no } = confirmData.value as any;
  parent_stock_code.value = stock_code;
  parent_serial_no.value = serial_no;
  dialogResult.value = false;
}

  watch(()=> (tablePagination.value.page), (val)=> {
    state.pagination = {
      ...state.pagination,
      page_num: val
    }
    selectDepotListFn();
}, {
  immediate: true,
})


</script>
<style scoped lang="scss">
  .searchIcon {
    width: 34px;
    height: 34px;
    margin-right: 10px;
  }
  .content {
    width: 100%;
    margin: 0 auto;
  }
  .flex1 {
    flex: 1;
  }
  .mt20 {
    margin-top: 20px;
  }
  .flex-center {
    display: flex;
    justify-content: center;
  }
  .overflow-hidden {
    overflow: hidden;
  }

  .cap {
    text-transform: capitalize;
  }
  .q-table--horizontal-separator thead th {
    border-color: transparent !important;
    border-top-width: 0 !important;
  }
  .title {
    padding: 16px;
    font-size: 18px !important;
  }
  .delImgClass {
    width: 20px;
    height: 20px;
  }
  .serialNoClass {
    flex-direction: column;
    justify-content: flex-start !important;
    align-items: flex-start;
    padding: 0 16px 16px 16px;
  }
  .fs18 {
    font-style: 18px;
  }
  table {
  border-collapse: collapse;
  table-layout: fixed;
}

table thead tr th {
  border-bottom: 1px solid white;
}

table th {
  color: #000;
}

table th,
table td {
  /* Added padding for better layout after collapsing */
  padding: 4px 8px;
}

table thead {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 10;
}

table tbody tr {
  border-top: 1px solid white;
  border-bottom: 1px solid #0000001f;

  &:hover {
    opacity: 0.9;
  }
}

table tbody tr,
table tbody td {
  height: 46px !important;
}

.pointer-cursor {
  cursor: pointer;
}

.pined-row-seperator {
  text-align: center;
}

.table-algin {
  text-align: center;
}
.justify-center {
    display: flex;
    justify-content: center;
}
</style>
